package com.chen.qq;

import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;

import javax.swing.JLabel;

/**
 * @author 5
 * 
 */
public class ImageLabel extends JLabel {

	private static final long serialVersionUID = -6322448161539344158L;

	private boolean rollover;

	private Image image;

	private static final Color color = new Color(210, 223, 233);

	public ImageLabel() {
		this(null);
	}

	public ImageLabel(Image img) {
		this.image = img;
		this.setHorizontalAlignment(JLabel.CENTER);
		this.setForeground(Color.white);
		this.setFont(new Font("dialog", Font.PLAIN, 15));
	}

	@Override
	protected void paintComponent(Graphics g) {
		if (image != null) {
			g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
			if (rollover) {
				Graphics2D g2d = (Graphics2D) g.create();

				if (Context.isNotEmpty(getText())) {
					g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f));
					g2d.setColor(Color.DARK_GRAY);
					g2d.fillRect(0, 0, getWidth(), getHeight());
					super.paintComponent(g);
				}

				g2d.setColor(Color.CYAN);
				g2d.setStroke(new BasicStroke(2));
				g2d.drawRect(1, 1, getWidth() - 2, getHeight() - 2);
				g2d.dispose();
			}
		} else {
			g.setColor(color);
			g.fillRect(0, 0, getWidth(), getHeight());
			g.setColor(Color.white);
			g.drawRect(0, 0, getWidth(), getHeight());
		}
	}

	public Image getImage() {
		return image;
	}

	public void setImage(Image image) {
		this.image = image;
		setOpaque(image == null);
		repaint();
	}

	public boolean isRollover() {
		return rollover;
	}

	public void setRollover(boolean rollover) {
		this.rollover = rollover;
		repaint();
	}

	@Override
	public Dimension getPreferredSize() {
		return image != null ? new Dimension(image.getWidth(null), image.getHeight(null)) : super
				.getPreferredSize();
	}
}
